#!/usr/bin/python
# -*-coding:utf-8 -*-
import socket
import cv2
import numpy
import struct
import json
import os
from time import sleep

res = []


def allfile(basepath):
    for item in os.listdir(basepath):
        path = os.path.join(basepath, item)
        if os.path.isfile(path):
            print(path)
            res.append(path)
        else:
            allfile(path)
    return res


# socket.AF_INET 用于服务器与服务器之间的网络通信
# socket.SOCK_STREAM 代表基于TCP的流式socket通信
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务端
address_server = ('10.10.10.51', 6667)
sock.connect(address_server)

files = allfile("test_0602")
num_file = len(files)

i = 0

"""
可以看做应用层协议头  共16个字节。
    1-4字节：1代表分类
    5-8字节：224代表图片宽
    9-12字节：224代表图片高
    13-16字节：1代表分类，图片分成几个等分传输。
"""
sock.send(struct.pack("iiii", 1, 224, 224, 1))
while 1:
    frame_src = cv2.imread(files[i % num_file])
    frame_gray = cv2.cvtColor(frame_src, cv2.COLOR_BGR2GRAY)
    frame_gray = cv2.cvtColor(frame_gray, cv2.COLOR_GRAY2BGR)
    frame_show = cv2.resize(frame_src, (640, 480))
    i = i + 1
    frame_send = cv2.resize(frame_gray, (224, 224))
    cv2.imshow("frame_send", frame_send)
    data = numpy.array(frame_send)
    stringData = data.tobytes()
    sock.send(stringData)
    # 发4个字节，2代表最后一包,1代表非最后一包
    sock.send(struct.pack("i", 2))
    temp_buf = sock.recv(1024)
    res_str = str(temp_buf)
    res_data = json.loads(res_str[2:-3])
    cv2.putText(frame_show, res_data['label'], (25, 30), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 23, 0), 2)
    # cv2.rectangle(frame, (res_data['rect']['x'], res_data['rect']['y']),
    #              (res_data['rect']['x'] + res_data['rect']['w'], res_data['rect']['y'] + res_data['rect']['h']),
    #              (0, 255, 0), 2)
    cv2.imshow("frame_show", frame_show)
    if cv2.waitKey(600) & 0xFF == ord('q'):
        break

sock.close()
cv2.destroyAllWindows()
